/**
 * @version		$Id: uploads.js 131 2011-04-01 16:26:21Z happy_noodle_boy $
 * @package		JCE
 * @copyright	Copyright (C) 2010 Ryan Demmer. All rights reserved.
 * @license		GNU/GPL
 * This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 */
(function($) {
    $.jce.Uploads = {
        options : {
            labels : {
                browse 	: 'Browse',
                alert 	: 'Incorrect file type'
            },
            extensions 	: ['xml'],
            readonly	: false,
            width		: 200,
            task		: null,
            button		: null,
            iframe		: false,
            report		: null
        },

        /**
         * Initilaise plugin
         * @param {Object} elements INPUT FILE elements to process
         * @param {Object} options Options object
         */
        init: function(options) {
            var t = this;
            $.extend(this.options, options);

            var readonly = this.options.readonly;
            var re = '.(' + this.options.extensions.join('|') + ')$';

            if (this.options.iframe) {
                var iframe = this.createIFrame();
            }

            $('input[type="file"]').each( function() {
                var d = document, el = this;

                var container 	= d.createElement('div');
                var input 		= d.createElement('input');
                var button 		= d.createElement('button');
                var span 		= d.createElement('span');

                $(container).addClass('upload_container').insertBefore(this).append(this).hover(function() {
                	$(button).addClass('ui-state-hover');
                }, function(){
                	$(button).removeClass('ui-state-hover');
                });

                $(input).attr({
                    'type' 		: 'text',
                    'name'		: $(this).attr('name') + '_input'
                }).addClass('ui-widget-content upload_text ui-corner-all').css({
                    'width': t.options.width
                });

                if (readonly) {
                    $(input).attr('readonly', 'readonly').appendTo($(container));
                } else {
                    $(input).insertBefore($(container));
                }

                $(span).addClass('upload_clear ui-icon ui-icon-circle-close').css('opacity', 0.15).insertBefore($(container)).click( function() {
                    $(input).val('').focus();
                    $(el).val('');
                });

                $(button).html(t.options.labels.browse).button({
                    icons: {
                        primary: 'browse'
                    }
                }).css('position', 'static').click( function(e) {
                    e.preventDefault();
                })

                // hide file input element
                $(this).css({
                    'opacity' : 0
                });
                
                // check for placeholder and create
            	if (!$.support.placeholder) {
            		// create javascript placeholder
                    $.jce.addPlaceHolder(input);
            	}

                // remove value on click if file input
                $(input).click( function() {
                    if (el.value) {
                        $(this).val('');
                        el.value = '';
                    }
                });

                $(button).insertBefore($(el));

                // submit button
                if (t.options.button) {
                    var btn = document.getElementById(t.options.button), submit = t.options.submit;

                    $(btn).click( function(e) {
                        if ($(input).hasClass('placeholder')) {
                            $(input).val('');
                        }

                        if (iframe) {
                            // Set Target
                            $('form').attr('target', iframe.name);
                        }

                        if (el.value || $(input).val()) {
                            $(this).addClass('loading');
                            $('input[name="task"]').val(t.options.task || '');
                            $('form').submit();
                        }

                        e.preventDefault();
                    }).button({
	                    icons: {
	                        primary: 'import'
	                    }
	                });
                    
                    $(container).append(btn);
                }

                // some IE6 support
                if (!window.XMLHttpRequest) {
                    $(this).addClass('ie_upload_input_file');
                    $(input).addClass('ie_input_text');
                    $(button).addClass('ie_button');
                }
            }).change( function() {
                var el = this;

                file = t.getFileName(el.value);

                if (!new RegExp(re).test(file)) {
                    alert(t.options.labels.alert);
                    el.value = '';
                } else {
                    $(el).parent('div.upload_container').siblings('input[name="'+ $(el).attr('name') + '_input"]').val(file).addClass('upload_file').removeClass('placeholder');
                }
            });

        },

        createIFrame : function() {
            var t = this;
            var iframe 	= document.createElement('iframe');
            var form 	= $('form');

            $(iframe).attr({
                'src' 	: 'javascript:""',
                'name'	: 'upload_iframe',
                'id'	: 'upload_iframe'
            }).hide().load( function(e) {
                var n = e.target, el;

                try {
                    el = n.contentWindow.document || n.contentDocument || window.frames[n.id].document;
                } catch (ex) {
                    alert("UPLOAD_SECURITY_ERROR");
                    return;
                }
                // Return on first load
                if (el.location.href == 'about:blank') {
                    return;
                }
                // Get result
                var result = el.body.innerHTML || el.documentElement.innerText || el.documentElement.textContent;

                // Assume no error
                if (result != '') {
                    $('form').removeAttr('target');
                    // append result
                    if (!document.getElementById(t.options.report)) {
                        $('form').prepend('<div id="'+ t.options.report +'"></div>');
                    }
                    $('form div#' + t.options.report).hide().html(result).fadeIn();
                }
                if (t.options.button) {
                    var btn = document.getElementById(t.options.button);
                    $(btn).removeClass('loading');
                }

            }).appendTo('form');

            // Change iframe name
            if (!$.support.cssFloat) {
                window.frames['upload_iframe'].name = 'upload_iframe';
            }

            // create iframe marker
            var input = document.createElement('input');

            $(input).attr({
                'type' 	: 'hidden',
                'name'	: 'method'
            }).val('iframe').appendTo('form');

            return iframe;
        },

        getFileName : function(file) {
            file = file.replace(/\\/g, '/');
            return file.substring(file.lastIndexOf('/') + 1);
        }

    }
})(jQuery);